<template>
  <BasicModal v-bind="$attrs" @register="registerModal" title="共享设置" :maskClosable="false" :closable="false" @ok="handleSubmit" width="550px">
    <div class="folder-name">
      <span class="folder-name-text">文件夹名称</span>
      <a-input placeholder="请输入文件夹名称" type="text" class="ant-input txt-folder-name" v-model:value="formData.fileName" :disabled="isUpdate" />
      <Icon
        icon="ant-design:star-filled"
        class="add-folder-star"
        :style="
          formData.isStar == '1'
            ? 'font-size: 16px; color: rgb(251, 192, 45); display: inline-flex;'
            : 'font-size: 16px; color: rgb(153, 161, 171); display: inline-flex'
        "
        @click="handleStar"
      />
    </div>
    <div class="folder-belong">
      <span class="folder-name-text">文件夹归属</span>
      <span v-if="isUpdate" class="txt-folder-name" style="font-size: 13px; line-height: 35px">{{ folderOwnershipLable }}</span>
      <a-select v-else v-model:value="formData.folderOwnership" style="width: 324px" :options="folderOwnershipOptions" />
    </div>
    <div class="folder-members">
      <div v-show="izOwner || izAdmin" class="folder-member-box">
        <div class="add-user-member pointer" @click="handleSelectConcertUser()">
          <Icon icon="ant-design:plus-circle-outlined" class="add-icon-user" style="font-size: 16px; display: inline-flex" />
          <span>添加协作者</span>
        </div>
      </div>
      <div class="nano-con"
        ><ul class="member-list">
          <li v-for="(item, index) in formData.userData" :key="item.id" class="member-item">
            <span class="img-member-box"> <img class="img-charge circle" :src="item.avatar" /> </span>
            <span class="member-name ellipsis">{{ item.realname }}</span>
            <span class="permission">
              <span v-if="item.authority == 'owner'" class="owner" style="width: 85px">拥有者</span>
              <span v-else-if="!izOwner && !izAdmin" style="width: 85px">{{ item.authorityLabel }}</span>
              <a-select
                v-else
                v-model:value="item.authority"
                style="width: 85px"
                :options="folderPermissionOptions"
                @change="handleAuthorityChange(item)"
              />
            </span>
            <span v-if="isUpdate && item.authority == 'owner' && userId == item.userId" class="entrusted-folder" @click="handleSelectEntrustedUser()">
              托付文件夹
            </span>
            <span v-else-if="isUpdate && userId == item.userId && item.authority != 'owner'" class="entrusted-folder" @click="handleUserExit(item)">
              退出
            </span>
            <span v-else-if="izOwner" class="remove-user" @click="handleUserRemove(item)"> 移除 </span>
          </li>
        </ul>
      </div>
    </div>
    <template #footer>
      <!-- <PopConfirmButton title="确定放弃编辑？" @confirm="closeDrawer" okText="创建文件夹" cancelText="取消">创建文件夹</PopConfirmButton> -->
      <a-button @click="handleCancel()" style="margin-right: 0.8rem">取消</a-button>
      <a-button v-if="!isUpdate" @click="handleSubmit()" type="primary" :loading="loading">创建文件夹</a-button>
    </template>
  </BasicModal>
  <UserSelectByDepModal :rowKey="rowKey" :labelKey="labelKey" @register="regConcertModal" @getSelectResult="setConcertUserSelectValue" />
  <UserSelectByDepModal
    :rowKey="rowKey"
    :labelKey="labelKey"
    :isRadioSelection="isRadioSelection"
    @register="regEntrustedModal"
    @getSelectResult="setEntrustedUserSelectValue"
  />
</template>
<script lang="ts" setup>
  import { ref, unref, reactive } from 'vue';

  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { useModal } from '/@/components/Modal';
  import UserSelectByDepModal from '/@/components/Form/src/jeecg/components/modal/UserSelectByDepModal.vue';
  import { useUserStore } from '/@/store/modules/user';
  import { message } from 'ant-design-vue';
  import {
    createAFolder,
    getShareFolder,
    changeStar,
    addAuthUser,
    deleteAuth,
    changeAuth,
    entrustedFolder,
    findUsersByIds,
    getUserTenants,
  } from '../files.api';
  import { folderPermissionOptions } from '../files.data';
  import { propTypes } from '/@/utils/propTypes';

  // Emits声明
  const emit = defineEmits(['register', 'success']);
  const userStore = useUserStore();
  const isUpdate = ref(true);
  const loading = ref(false);
  // 属性
  const props = defineProps({
    value: propTypes.oneOfType([propTypes.string, propTypes.array]),
    rowKey: {
      type: String,
      default: 'id',
    },
    labelKey: {
      type: String,
      default: 'realname',
    },
    isRadioSelection: {
      type: Boolean,
      default: true,
    },
  });

  // 表单提交
  const formData = reactive({
    id: '',
    fileName: '',
    fileType: 'folder',
    isFolder: '1',
    isRootFolder: '1',
    storeType: 'manage',
    isStar: '0',
    userData: [] as Array,
    folderOwnership: '个人',
  });

  //当前用户ID
  const userId = userStore.getUserInfo.id;
  //文件信息
  const sysFile = ref();
  //文件夹归属
  const folderOwnershipOptions: Array = ref([]);
  const folderOwnershipLable = ref('');
  //是否为拥有者
  const izOwner = ref(false);
  //是否为拥有者
  const izAdmin = ref(false);

  //注册model
  const [regConcertModal, { openModal: openConcertModal }] = useModal();
  const [regEntrustedModal, { openModal: openEntrustedModal }] = useModal();

  //表单赋值
  const [registerModal, { setModalProps, closeModal, redoModalHeight }] = useModalInner(async (data) => {
    //重置表单
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    formData.userData = [];
    folderOwnershipOptions.value = [];
    izOwner.value = false;
    izAdmin.value = false;
    if (unref(isUpdate)) {
      await reloadFolderData(data.record.fileId);
    } else {
      formData.id = '';
      formData.fileName = '';
      formData.fileType = 'folder';
      formData.isFolder = '1';
      formData.isRootFolder = '1';
      formData.isStar = '0';
      formData.userData = [];
      formData.folderOwnership = '个人';
      izOwner.value = true;
      izAdmin.value = false;
      pushConcertUser({
        fileId: '',
        userId: userStore.getUserInfo.id,
        authority: 'owner',
        realname: userStore.getUserInfo.realname,
        avatar: userStore.getUserInfo.avatar,
        tenantId: userStore.getUserInfo.tenantId,
      });
    }
    loadFolderOwnershipOptions();
  });

  /**
   * 重新加载目录数据
   */
  async function reloadFolderData(fileId) {
    const result = await getShareFolder({ fileId: fileId });
    sysFile.value = result.sysFile;
    formData.id = result.sysFile.id;
    formData.fileName = result.sysFile.fileName;
    formData.fileType = result.sysFile.fileType;
    formData.isFolder = result.sysFile.isFolder;
    formData.isRootFolder = result.sysFile.isRootFolder;
    formData.isStar = result.sysFile.isStar;
    formData.userData = [];
    formData.folderOwnership = result.sysFile.folderOwnership;

    izOwner.value = false;
    izAdmin.value = false;
    result.authVoList.forEach((item) => {
      pushConcertUser({
        fileId: '',
        userId: item.userId,
        authority: item.authority,
        realname: item.realname,
        avatar: item.avatar,
        tenantId: item.tenantId,
      });
      if (item.userId == userId && item.authority == 'owner') {
        izOwner.value = true;
      } else if (item.userId == userId && item.authority == 'admin') {
        izAdmin.value = true;
      }
    });
  }

  /**
   * 设置协作用户
   */
  async function setConcertUserSelectValue(options, values) {
    const params = {
      ids: values.join(','),
    };
    const addAuthUserList: Array = [];
    let data = await findUsersByIds(params);
    data.forEach((item) => {
      addAuthUserList.push({
        fileId: formData.id,
        userId: item.id,
        authority: 'editable',
        realname: item.realname,
        avatar: item.avatar,
        tenantId: item.tenantId,
      });
      pushConcertUser(addAuthUserList[addAuthUserList.length - 1]);
    });
    if (isUpdate.value) {
      await addAuthUser(addAuthUserList);
    }
  }

  /**
   * 设置托付文件夹用户
   */
  async function setEntrustedUserSelectValue(options, values) {
    if (unref(values).length > 1) {
      message.warn('托付文件夹用户不能为多个用户');
      return;
    }
    const params = {
      fileId: formData.id,
      userId: userId,
      toUserId: values[0],
    };
    await entrustedFolder(params, async function () {
      await reloadFolderData(formData.id);
    });
  }

  /**
   * 加载共享文件归属
   */
  async function loadFolderOwnershipOptions() {
    folderOwnershipOptions.value.push({
      value: '个人',
      label: '个人',
    });
    const tenantData = await getUserTenants();
    if (tenantData.list) {
      tenantData.list.forEach((item) => {
        folderOwnershipOptions.value.push({
          value: item.id,
          label: item.name,
        });
      });
    }
    if (unref(isUpdate)) {
      folderOwnershipOptions.value.forEach((item) => {
        if (item.value == formData.folderOwnership) {
          folderOwnershipLable.value = item.label;
        }
      });
    }
  }

  /**
   * 获得协作者权限名称
   */
  async function getAuthorityLabel(value) {
    let label = '';
    let hasAuthority = folderPermissionOptions.filter((item) => {
      return item.value == value;
    });
    if (unref(hasAuthority).length > 0) {
      label = hasAuthority[0].label;
    }
    return label;
  }

  /**
   * 添加协作者
   */
  async function pushConcertUser(item: any) {
    let arr = unref(formData.userData).filter((p) => p.userId == item.userId);
    if (unref(arr).length == 0) {
      const userItem = {
        fileId: item.fileId,
        userId: item.userId,
        authority: item.authority,
        authorityLabel: await getAuthorityLabel(item.authority),
        realname: item.realname,
        avatar: item.avatar,
      };
      if (userItem.authority == 'owner') {
        formData.userData.splice(0, 0, userItem);
      } else {
        formData.userData.push(userItem);
      }
    }
    redoModalHeight();
  }

  /**
   * 移除协作者
   */
  async function popuConcertUser(item: any) {
    const arr = unref(formData.userData).filter((p) => p.userId != item.userId);
    formData.userData = arr;
    redoModalHeight();
  }

  /**
   * 标星
   */
  async function handleStar() {
    const starFlag = formData.isStar == '1' ? '0' : '1';
    if (unref(isUpdate)) {
      const params = { fileId: sysFile.value.id, isStar: starFlag };
      await changeStar(params, function () {
        formData.isStar = starFlag;
      });
    } else {
      formData.isStar = starFlag;
    }
  }

  /**
   * 协作用户选择
   */
  async function handleSelectConcertUser() {
    openConcertModal(true, {
      isUpdate: false,
    });
  }

  /**
   * 文件夹托付用户选择
   */
  async function handleSelectEntrustedUser() {
    openEntrustedModal(true, {
      isUpdate: false,
    });
  }

  /**
   * 用户权限变更
   */
  async function handleAuthorityChange(item) {
    if (unref(isUpdate)) {
      const params = { fileId: sysFile.value.id, userId: item.userId, authority: item.authority };
      await changeAuth(params);
      await reloadFolderData(formData.id);
    }
  }

  /**
   * 用户移除
   */
  async function handleUserRemove(item: any) {
    if (unref(isUpdate)) {
      const params = { fileId: sysFile.value.id, userId: item.userId };
      await deleteAuth(params, function () {
        popuConcertUser(item);
      });
    } else {
      popuConcertUser(item);
    }
  }

  /**
   * 用户退出
   */
  async function handleUserExit(item: any) {
    if (unref(isUpdate)) {
      const params = { fileId: sysFile.value.id, userId: item.userId };
      await deleteAuth(params, function () {
        popuConcertUser(item);
      });
    }
  }

  /**
   * 关闭窗口
   */
  async function handleCancel() {
    closeModal();
    emit('success');
  }

  //创建目录
  async function handleSubmit() {
    try {
      if (formData.fileName.length == 0) {
        message.warn('请填写文件夹名称');
        return;
      }
      console.log(formData);
      setModalProps({ confirmLoading: true });
      //提交表单
      await createAFolder(formData);
      //关闭弹窗
      closeModal();
      //刷新列表
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
<style lang="less" scoped>
  @import '../less/LeftFile';
</style>
